package com.pai4j.ugc.service.community;

import com.pai4j.common.enums.ContributionActionEnum;
import com.pai4j.common.enums.ContributionStatusEnum;
import com.pai4j.domain.vo.request.community.ContributionStatusChangeRequestVO;
import com.pai4j.remote.user.UserServiceClient;
import com.pai4j.ugc.repository.dao.ICommunityContributionDAO;
import com.pai4j.ugc.repository.entity.CommunityContributionEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.pai4j.common.enums.MessageTypeEnum;
import com.pai4j.common.enums.messagequeue.MessageBroadChannelEnum;
import com.pai4j.common.service.messagequeue.producer.MessageQueueProducer;
import com.pai4j.common.util.DateUtils;
import com.pai4j.domain.vo.request.mess.MessageNotifyVO;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 社区共建工作流服务类
 *
 * @author: CYM-pai
 * @date: 2025/07/30 12:00
 **/
@Slf4j
@Service
public class CommunityContributionWorkflowService {

    @Autowired
    private ICommunityContributionDAO contributionDAO;
    @Autowired
    private CommunityContributionHistoryService historyService;
    @Autowired
    private MessageQueueProducer messageQueueProducer;
    @Autowired
    private UserServiceClient userServiceClient;

    /**
     * 变更共建状态
     *
     * @param statusChangeRequest 状态变更请求
     * @return 是否变更成功
     */
    public Boolean changeStatus(ContributionStatusChangeRequestVO statusChangeRequest) {
        // 1. 查询共建是否存在
        CommunityContributionEntity contributionEntity = 
                contributionDAO.findById(statusChangeRequest.getContributionId()).orElse(null);
        if (contributionEntity == null) {
            return false;
        }
        
        // 2. 验证状态流转是否合法
        if (!isValidStatusTransition(contributionEntity.getStatus(), statusChangeRequest.getNewStatus())) {
            log.warn("Invalid status transition from {} to {}", contributionEntity.getStatus(), statusChangeRequest.getNewStatus());
            return false;
        }
        
        // 3. 记录变更前的状态
        Integer oldStatus = contributionEntity.getStatus();
        String oldStatusName = getStatusName(oldStatus);
        String newStatusName = getStatusName(statusChangeRequest.getNewStatus());
        
        // 4. 更新状态
        contributionEntity.setStatus(statusChangeRequest.getNewStatus());
        contributionEntity.setUpdateBy(statusChangeRequest.getOperator());
        
        // 5. 处理分配逻辑
        if (StringUtils.hasText(statusChangeRequest.getAssignee())) {
            contributionEntity.setAssignee(statusChangeRequest.getAssignee());
        }
        
        // 6. 处理完成时间
        if (ContributionStatusEnum.COMPLETED.getStatus().equals(statusChangeRequest.getNewStatus())) {
            contributionEntity.setActualDate(new Date());
        }
        
        // 7. 保存变更
        contributionDAO.save(contributionEntity);
        
        // 8. 记录操作历史
        String description = String.format("状态从 %s 变更为 %s", oldStatusName, newStatusName);
        if (StringUtils.hasText(statusChangeRequest.getReason())) {
            description += "，原因：" + statusChangeRequest.getReason();
        }
        historyService.recordHistory(contributionEntity.getId(), statusChangeRequest.getOperator(), 
                ContributionActionEnum.STATUS_CHANGE.getAction(), oldStatusName, newStatusName, description);
        
        // 9. 发送状态变更通知
        sendStatusChangeNotification(contributionEntity, statusChangeRequest, oldStatusName, newStatusName);

        // 10. 添加状态变更评论
        if (StringUtils.hasText(statusChangeRequest.getReason())) {
            // 这里可以调用评论服务添加状态变更评论
            // commentService.create(...);
        }

        return true;
    }

    /**
     * 分配处理人
     *
     * @param contributionId 共建ID
     * @param assignee       处理人
     * @param operator       操作人
     * @return 是否分配成功
     */
    public Boolean assignContribution(Long contributionId, String assignee, String operator) {
        // 1. 查询共建是否存在
        CommunityContributionEntity contributionEntity = contributionDAO.findById(contributionId).orElse(null);
        if (contributionEntity == null) {
            return false;
        }
        
        // 2. 记录变更前的处理人
        String oldAssignee = contributionEntity.getAssignee();
        
        // 3. 更新处理人
        contributionEntity.setAssignee(assignee);
        contributionEntity.setUpdateBy(operator);
        contributionDAO.save(contributionEntity);
        
        // 4. 记录操作历史
        String description = String.format("分配处理人从 %s 变更为 %s",
                StringUtils.hasText(oldAssignee) ? oldAssignee : "无", assignee);
        historyService.recordHistory(contributionId, operator,
                ContributionActionEnum.ASSIGN.getAction(), oldAssignee, assignee, description);

        // 5. 发送分配通知
        sendAssignNotification(contributionEntity, assignee, operator);

        return true;
    }

    /**
     * 验证状态流转是否合法
     *
     * @param currentStatus 当前状态
     * @param newStatus     新状态
     * @return 是否合法
     */
    private boolean isValidStatusTransition(Integer currentStatus, Integer newStatus) {
        // 定义状态流转规则
        Map<Integer, Integer[]> transitionRules = new HashMap<>();
        
        // 已提交 -> 审核中、已拒绝
        transitionRules.put(ContributionStatusEnum.SUBMITTED.getStatus(), 
                new Integer[]{ContributionStatusEnum.REVIEWING.getStatus(), ContributionStatusEnum.REJECTED.getStatus()});
        
        // 审核中 -> 已接受、已拒绝
        transitionRules.put(ContributionStatusEnum.REVIEWING.getStatus(), 
                new Integer[]{ContributionStatusEnum.ACCEPTED.getStatus(), ContributionStatusEnum.REJECTED.getStatus()});
        
        // 已接受 -> 进行中、已拒绝
        transitionRules.put(ContributionStatusEnum.ACCEPTED.getStatus(), 
                new Integer[]{ContributionStatusEnum.IN_PROGRESS.getStatus(), ContributionStatusEnum.REJECTED.getStatus()});
        
        // 进行中 -> 已完成、已接受（回退）
        transitionRules.put(ContributionStatusEnum.IN_PROGRESS.getStatus(), 
                new Integer[]{ContributionStatusEnum.COMPLETED.getStatus(), ContributionStatusEnum.ACCEPTED.getStatus()});
        
        // 已完成 -> 进行中（重新打开）
        transitionRules.put(ContributionStatusEnum.COMPLETED.getStatus(), 
                new Integer[]{ContributionStatusEnum.IN_PROGRESS.getStatus()});
        
        // 已拒绝 -> 已提交（重新提交）
        transitionRules.put(ContributionStatusEnum.REJECTED.getStatus(), 
                new Integer[]{ContributionStatusEnum.SUBMITTED.getStatus()});
        
        // 检查是否允许流转
        Integer[] allowedStatuses = transitionRules.get(currentStatus);
        if (allowedStatuses == null) {
            return false;
        }
        
        for (Integer allowedStatus : allowedStatuses) {
            if (allowedStatus.equals(newStatus)) {
                return true;
            }
        }
        
        return false;
    }

    /**
     * 获取状态名称
     */
    private String getStatusName(Integer status) {
        for (ContributionStatusEnum statusEnum : ContributionStatusEnum.values()) {
            if (statusEnum.getStatus().equals(status)) {
                return statusEnum.getStatusName();
            }
        }
        return "未知状态";
    }

    /**
     * 发送状态变更通知
     */
    private void sendStatusChangeNotification(CommunityContributionEntity contributionEntity,
                                            Object statusChangeRequest,
                                            String oldStatusName,
                                            String newStatusName) {
        try {
            // 获取提交人信息
            String submitter = contributionEntity.getSubmitter();
            if (!StringUtils.hasText(submitter)) {
                log.warn("共建提交人为空，无法发送通知: contributionId={}", contributionEntity.getId());
                return;
            }

            // 构建通知消息
            String notificationMessage = String.format(
                "您提交的%s《%s》状态已更新：%s → %s",
                contributionEntity.getType() == 1 ? "需求" : "Bug",
                contributionEntity.getTitle(),
                oldStatusName,
                newStatusName
            );

            // 创建通知消息VO
            MessageNotifyVO messageNotifyVO = new MessageNotifyVO();
            messageNotifyVO.setSenderId("SYSTEM"); // 系统发送
            messageNotifyVO.setReceiverId(submitter);
            messageNotifyVO.setMessage(notificationMessage);
            messageNotifyVO.setTime(DateUtils.getCurrentTimeMillis());
            messageNotifyVO.setType(MessageTypeEnum.SYSTEM.getType());

            // 发送通知到消息队列
            messageQueueProducer.broadSend(MessageBroadChannelEnum.QUEUE_INTERACTION_NOTIFY, messageNotifyVO);

            log.info("共建状态变更通知发送成功: contributionId={}, submitter={}, status={}→{}",
                    contributionEntity.getId(), submitter, oldStatusName, newStatusName);

        } catch (Exception e) {
            // 通知发送失败不影响主业务，只记录日志
            log.error("发送共建状态变更通知失败: contributionId={}", contributionEntity.getId(), e);
        }
    }

    /**
     * 发送分配通知
     */
    private void sendAssignNotification(CommunityContributionEntity contributionEntity,
                                      String assignee,
                                      String operator) {
        try {
            // 发送给被分配的处理人
            if (StringUtils.hasText(assignee)) {
                String assigneeMessage = String.format(
                    "您被分配处理%s《%s》，请及时查看并处理",
                    contributionEntity.getType() == 1 ? "需求" : "Bug",
                    contributionEntity.getTitle()
                );

                MessageNotifyVO assigneeNotifyVO = new MessageNotifyVO();
                assigneeNotifyVO.setSenderId(operator);
                assigneeNotifyVO.setReceiverId(assignee);
                assigneeNotifyVO.setMessage(assigneeMessage);
                assigneeNotifyVO.setTime(DateUtils.getCurrentTimeMillis());
                assigneeNotifyVO.setType(MessageTypeEnum.SYSTEM.getType());

                messageQueueProducer.broadSend(MessageBroadChannelEnum.QUEUE_INTERACTION_NOTIFY, assigneeNotifyVO);
            }

            // 发送给提交人
            String submitter = contributionEntity.getSubmitter();
            if (StringUtils.hasText(submitter) && !submitter.equals(assignee)) {
                String submitterMessage = String.format(
                    "您提交的%s《%s》已分配给 %s 处理",
                    contributionEntity.getType() == 1 ? "需求" : "Bug",
                    contributionEntity.getTitle(),
                    assignee
                );

                MessageNotifyVO submitterNotifyVO = new MessageNotifyVO();
                submitterNotifyVO.setSenderId("SYSTEM");
                submitterNotifyVO.setReceiverId(submitter);
                submitterNotifyVO.setMessage(submitterMessage);
                submitterNotifyVO.setTime(DateUtils.getCurrentTimeMillis());
                submitterNotifyVO.setType(MessageTypeEnum.SYSTEM.getType());

                messageQueueProducer.broadSend(MessageBroadChannelEnum.QUEUE_INTERACTION_NOTIFY, submitterNotifyVO);
            }

            log.info("共建分配通知发送成功: contributionId={}, assignee={}, operator={}",
                    contributionEntity.getId(), assignee, operator);

        } catch (Exception e) {
            log.error("发送共建分配通知失败: contributionId={}", contributionEntity.getId(), e);
        }
    }

    public Boolean assign(Long contributionId, String assignee, String operator) {



        return null;
    }
}
